package com.bfxy.rabbit.common.convert;

import com.google.common.base.Preconditions;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;

/**
 * @author caryguan
 * @version V1.0
 * @Package com.bfxy.rabbit.common.convert
 * @date 2020/10/2 12:15
 */
//装饰者模式 提高扩展性
public class RabbitMessageConverter implements MessageConverter {
    private GenericMessageConverter delegate;

    private final String defaultExpire = String.valueOf(24 * 60 * 60 * 1000);

    public RabbitMessageConverter(GenericMessageConverter genericMessageConverter) {
        Preconditions.checkNotNull(genericMessageConverter);
        this.delegate = genericMessageConverter;
    }

    @Override
    public Message toMessage(Object object, MessageProperties messageProperties) throws MessageConversionException {
        messageProperties.setExpiration(defaultExpire);
        // messageProperties.setDelay(1);
        this.delegate.toMessage(object, messageProperties);
        return null;
    }

    @Override
    public Object fromMessage(Message message) throws MessageConversionException {
        com.bfxy.rabbit.api.Message msg = (com.bfxy.rabbit.api.Message) this.delegate.fromMessage(message);
        return msg;

    }
}